package org.kl.wx.web;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.kl.bf.entity.easyui.EasyuiUtils;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.kl.wx.entity.WxUser;
import org.kl.wx.service.AppService;
import org.kl.wx.service.GroupsService;
import org.kl.wx.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

@Controller
@RequestMapping(value = "/wx/wxUser")
public class WxUserController extends BasicController {

	@Autowired
	private WxUserService wxUserService;

	@Autowired
	private GroupsService groupsService;

	@Autowired
	private AppService appService;

	@RequiresPermissions(value = "wxUser:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "wx/wxUserList";
	}

	@RequiresPermissions(value = "wxUser:list")
	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<WxUser> wxUser = wxUserService.getWxUser(searchParams, pageNumber, pageSize, sortType, orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(wxUser.getContent(), (int) wxUser.getTotalElements());
	}

	@RequiresPermissions(value = "wxUser:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("wxUser") WxUser wxUser, BindingResult result) {
		if (result.hasErrors()) {
			return ajaxMsg(bindingMsg(result), false, null);
		}
		try {
			wxUserService.saveWxUser(wxUser);
			return ajaxMsg("保存成功", true, null);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("保存失败", false, null);
		}
	}

	@RequiresPermissions(value = "wxUser:delete")
	@RequestMapping(value = "delete/{id}")
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes) {
		try {
			wxUserService.deleteWxUser(id);
			return ajaxMsg("删除成功", true, null);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败", false, null);
		}
	}

	// 获取用户列表
	@RequestMapping(value = "synUserList", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String synUserList(@RequestParam(value = "appId", defaultValue = "") String appId, HttpSession session) {
		try {
			WxMpService wxMpService = super.getWxMpServiceByAppId(session, appId);
			WxMpUserList wxMpUserList = wxMpService.userList(null);
			wxUserService.getWxUser(wxMpService, wxMpUserList, appId);
			return ajaxMsg("同步成功", true, wxMpUserList);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("同步失败", false, null);
		}
	}

	@RequiresPermissions({ "wxUser:delete" })
	@RequestMapping(value = "multiDelete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = wxUserService.multiDelete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("删除成功:" + msg, true, null);
	}

	@RequiresPermissions("wxUser:export")
	@RequestMapping(value = "excelExport", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExport(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model,
			ServletRequest request, HttpServletResponse response) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		List<WxUser> wxUsers = wxUserService.getAllWxUser(searchParams, sortType, orderType);
		super.export(WxUser.class, response, wxUsers, "微信用户信息");

		return null;
	}

	/**
	 * 通用查改增删，用于行编辑表格(表格式录入)
	 * 
	 * @return
	 */
	@RequestMapping(value = "crud", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String crud(@RequestParam(value = "inserted") String inserted,
			@RequestParam(value = "updated") String updated, @RequestParam(value = "deleted") String deleted,
			RedirectAttributes redirectAttributes) {
		System.out.print(updated);
		try {
			wxUserService.crud(inserted, updated, deleted);
			return ajaxMsg("保存成功", true, null);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("保存失败:<br>" + e.getMessage(), false, null);
		}
	}

	@ModelAttribute
	public void getWxUser(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("wxUser", wxUserService.getWxUser(id));
		}
	}

}
